import { minProgramAuthLogin, loginAccount } from "@/api/common";
import { UserTip } from "./constants";

export function wxLogin() {
    uni.login({
        provider: 'weixin',
        success: function (loginRes) {
            const { code } = loginRes
            wxAuthLogin(code)
        }
    });
}
/**
 * 
 * 微信授权登录
 */
async function wxAuthLogin(wxCode: string) {
    const result = await minProgramAuthLogin(wxCode) as { is_bind: number, code: string, open_id: string, user: any }
    if (result.is_bind == 0) {
        uni.redirectTo({
            url: '/subpackages/login/bindingAccount?wxCode=' + result.code + '&&openId=' + result.open_id,
        })
    } else {
        let user = result.user
        saveUserData(user)
        uni.switchTab({
            url: "/pages/index/index",
        });
        uni.showToast({
            title: "登录成功",
            icon: "success",
        });
    }
}
export function normalLogin(userName: string, password: string) {
    login(userName, password)
}
async function login(userName: string, password: string) {
    await loginAccount({
        name: userName,
        password: password,
        login_type: 3,
    })
        .then((data) => {
            uni.$emit('update', { formType: 'LOGIN' })
            saveUserData(data)
            if (password == "123456") {
                uni.navigateTo({
                    url: "/subpackages/modify/modifyPass",
                });
            } else {
                uni.switchTab({
                    url: "/pages/index/index",
                });
                uni.showToast({
                    title: "登录成功",
                    icon: "success",
                });
            }
        })
        .catch((error) => { });
}

export function saveUserData(user: any) {
    uni.setStorageSync(UserTip.USER_DATA, JSON.stringify(user))
    uni.setStorageSync(UserTip.TOKEN, user.token);
}

export function reomveUserData(jumpLogin: boolean) {
    uni.removeStorageSync(UserTip.USER_DATA);
    uni.removeStorageSync(UserTip.TOKEN);
    if (jumpLogin) {
        uni.reLaunch({
            url: '/subpackages/login/login',
        })
    }

}
export function saveUserCityCode(cityCode) {
    uni.setStorageSync(UserTip.USER_CITY_CODE, JSON.stringify(cityCode))
}
export function userToken(): string {
    return "Bearer " + uni.getStorageSync('token')
}